package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.message.FollowBehaviorConstants;
import com.heima.common.constants.user.UserFollowConstants;
import com.heima.common.exception.CustomException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.behavior.dtos.FollowBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFan;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.user.mapper.ApUserFanMapper;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserRelationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Slf4j
@Service
@Transactional
public class ApUserRelationServiceImpl implements ApUserRelationService {
    @Autowired
    ArticleFeign articleFeign;

    /**
     * 用户关注/取消关注
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(UserRelationDto dto) {
        //1.检查参数
        if (dto == null || dto.getOperation() < 0 || dto.getOperation() > 1) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2 判断是否有作者
        if (dto.getAuthorId() == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "作者ID不存在");
        }
        ApAuthor apAuthor = articleFeign.selectById(dto.getAuthorId());
        if (apAuthor == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "作者信息不存在");
        }
        if (dto.getArticleId() == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "文章ID不存在");
        }
        //3 判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "当前用户未登录，无法关注");
        }
        // 关注
        if (dto.getOperation() == UserFollowConstants.FOLLOW_UP) {
            //4 创建数据（app用户关注和app用户粉丝）
            return followByUserId(user.getId(), apAuthor.getUserId(),dto.getArticleId());
        }
        if (dto.getOperation() == UserFollowConstants.FOLLOW_DOWN) {
            return followCancelByUserId(user.getId(), apAuthor.getUserId());
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "返回错误信息");
    }
    /**
     * 取消关注
     * @param userId   普通用户（当前登录人）
     * @param followUserId 被关注的作者对应的apUser id
     * @return
     */
    private ResponseResult followCancelByUserId(Integer userId, Integer followUserId) {
        // 删除当前用户关注信息
        apUserFollowMapper.delete(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getFollowId, followUserId)
                .eq(ApUserFollow::getUserId, userId));
        // 删除被关注的粉丝信息
        apUserFanMapper.delete(Wrappers.<ApUserFan>lambdaQuery()
                .eq(ApUserFan::getFansId, userId)
                .eq(ApUserFan::getUserId, followUserId));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Autowired
    ApUserMapper apUserMapper;
    @Autowired
    ApUserFollowMapper apUserFollowMapper;
    @Autowired
    ApUserFanMapper apUserFanMapper;
    @Autowired
    KafkaTemplate kafkaTemplate;

    /**
     * 关注
     *
     * @param userId       普通用户（当前登录人）
     * @param followUserId 被关注的作者对应的apUser id
     * @return
     */
    private ResponseResult followByUserId(Integer userId, Integer followUserId, Long articleId ) {
        //1.获取被关注的作者对应的apUser
        ApUser followUser = apUserMapper.selectById(followUserId);
        if (followUser == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "被关注用户不存在");
        }
        //查询用户
        ApUser apUser = apUserMapper.selectById(userId);
        if (apUser == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
        }
        if (userId.intValue() == followUser.getId().intValue()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "无需关注自己");
        }
        //2 保存当前用户关注信息
        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getFollowId, followUserId)
                .eq(ApUserFollow::getUserId, userId));
        if (apUserFollow != null) {
            throw new CustomException(AppHttpCodeEnum.DATA_EXIST, "您已经关注该用户，无需重复关注");
        }
        //创建apUserFollow对象
        apUserFollow = new ApUserFollow();
        apUserFollow.setFollowId(followUserId);
        apUserFollow.setUserId(userId);
        apUserFollow.setLevel((short) 1);
        apUserFollow.setIsNotice(true);
        apUserFollow.setFollowName(followUser.getName());
        apUserFollow.setCreatedTime(new Date());
        apUserFollowMapper.insert(apUserFollow);
        //3 保存 被关注的作者对应的apUser 对应的粉丝（当前用户）
        ApUserFan apUserFan = apUserFanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery()
                .eq(ApUserFan::getFansId, userId)
                .eq(ApUserFan::getUserId, followUserId));
        if (apUserFan != null) {
            throw new CustomException(AppHttpCodeEnum.DATA_EXIST, "您已经关注该用户，无需重复关注");
        }
        //创建ApUserFan对象
        apUserFan = new ApUserFan();
        apUserFan.setUserId(followUserId);
        apUserFan.setCreatedTime(new Date());
        apUserFan.setLevel((short)0);
        apUserFan.setIsShieldComment(false);
        apUserFan.setIsShieldLetter(false);
        apUserFan.setIsDisplay(true);
        apUserFan.setFansId(userId.longValue());
        // 粉丝名称
        apUserFan.setFansName(apUser.getName());
        apUserFanMapper.insert(apUserFan);
        //记录啊用户的行为
// 记录关注行为
        FollowBehaviorDto dto = new FollowBehaviorDto();
        dto.setFollowId(followUserId);
        dto.setArticleId(articleId);
        dto.setUserId(apUser.getId());
//异步发送消息，保存关注行为
        kafkaTemplate.send(FollowBehaviorConstants.FOLLOW_BEHAVIOR_TOPIC, JSON.toJSONString(dto));
        // 返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
